package dimension.starry.block.machine.simple.weaponTable;

import dimension.starry.StarryDimension;
import dimension.starry.block.machine.simple.SimpleMachineRegister;
import dimension.starry.block.typeInterface.MachineTileEntity;
import dimension.starry.item.ItemRegisterManager;
import dimension.starry.item.typeInterface.WeaponType.WeaponType;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

/**
 * @author 150149
 */
public class WeaponTableTileEntity extends MachineTileEntity {

    private static final Text TITLE = Text.translatable("block." + StarryDimension.MOD_ID + ".weapon_table");

    public WeaponTableTileEntity(BlockPos blockPos, BlockState blockState) {
        super(SimpleMachineRegister.WEAPON_TABLE.getBlockEntityType(), blockPos, blockState, 3, TITLE, 800);
    }

    @Override
    public ScreenHandler createMenu(int sycID, PlayerInventory inventory, PlayerEntity player) {
        return new WeaponTableContainer(
            SimpleMachineRegister.WEAPON_TABLE.getScreenHandlerType(), sycID, inventory, getPos());
    }

    private int getExperiencePoints(Item item) {
        if (item.getTranslationKey().equals(ItemRegisterManager.SHAPED_POWDER.getItem().getTranslationKey())) {
            return 500;
        }
        return 0;
    }

    @Override
    public void tick(World world, BlockPos pos, BlockState state1, MachineTileEntity blockEntity) {
        if (world == null || world.isClient()) {
            return;
        }
        ItemStack weaponItemStack = this.inventory.getStack(0);
        ItemStack inputItemStack = this.inventory.getStack(1);

        if (weaponItemStack.isEmpty() || inputItemStack.isEmpty()) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (!(weaponItemStack.getItem() instanceof WeaponType)) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (getExperiencePoints(inputItemStack.getItem()) == 0) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (!this.inventory.getStack(2).isEmpty()) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (WeaponType.getLevel(weaponItemStack) < WeaponType.getMaxLevel(weaponItemStack)) {
            inputItemStack.setCount(inputItemStack.getCount() - 1);
            WeaponType.addExp(weaponItemStack, getExperiencePoints(inputItemStack.getItem()));
            this.inventory.setStack(0, ItemStack.EMPTY);
            this.inventory.setStack(2, weaponItemStack);
            this.resetProgress();
        }
    }


}
